<template>
    <div class="out-style">
         <!-- -{{type}}- -->
        <Row :gutter="16">
            <Col span="8">
                <span class="tow-line-font">必须使用Excel模板进行数据导入，禁止对模板表结构进行修改</span>
            </Col>
            <Col span="12">
                <span class="tow-line-font2">
                    <a :href="templateHref" target="_Blank">点击下载 {{typeName}} Excel导入模板</a>
                </span>
            </Col>
        </Row>
        <Row type="flex" justify="center">
            <Col span="24">
                <div class="step-style">
                    <Steps :current="state">
                        <Step title="上传Excel"></Step>
                        <Step title="预览数据"></Step>
                        <Step title="导入数据"></Step>
                    </Steps>
                </div>
            </Col>
        </Row>
        <div v-show="state === 0">
            <Row>
                <Col span="24">
                    <div class="four-line-font">您将通过上传的Excel文件，批量追加表格数据</div>
                    <div class="four-line-font">导入后只会保留Excel中的数据及通过公式计算后的值，设置的文字颜色等样式、合并的单元格、以及计算公式本身都不会被保留。</div>
                </Col>
            </Row>
            <Row v-if="false">
              <Col span="24">
                <transition name="fade">
                    <Progress v-if="showProgress" :percent="progressPercent" :stroke-width="2">
                        <div v-if="progressPercent == 100">
                            <Icon type="ios-checkmark-circle"/>
                            <span>成功</span>
                        </div>
                    </Progress>
                </transition>
              </Col>
            </Row>
            <Row>
                <Col span="24">
                    <div class="last-line-upload">
                        <Spin size="large" fix v-if="tableLoading"></Spin>
                        <Upload
                                :before-upload="handleBeforeUpload"
                                action=""
                                accept=".xls, .xlsx"
                                type="drag">
                            <div class="upload-tip">
                                <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                <p>请导入.xls或.xlsx格式的Excel</p>
                            </div>
                        </Upload>
                    </div>
                </Col>
            </Row>
        </div>
        <div v-show="state === 1">
            <Row>
              <Col span="4">
                <div v-if="file !== null" class="ivu-upload-list-file">
                    <Icon type="ios-stats"/>
                    {{ file.name }}
                    <Icon v-show="showRemoveFile" type="ios-close" class="ivu-upload-list-remove"
                          @click.native="handleRemove()"/>
                </div>
              </Col>
            </Row>
            <Row>
              <Col span="24">
                <Alert type="warning" style="font-size: 18px; margin-top: 10px;" v-if="nextBtnDisabled">
                    错误类型：
                    <Avatar shape="square" style="width:100px;color: #ED4014;background-color: #FFEFE6;margin-right: 5px;">格式有误</Avatar>
                    <Avatar shape="square" style="width:100px;color: #fff;background-color: #187;margin-right: 5px;">数据重复</Avatar>
                    <Avatar shape="square" v-if="type == 'all'" style="width:200px;color: #0032a0;background-color: #b0bbd3;margin-right: 5px;">人员不存在或已转送</Avatar>
                </Alert>
                <vxe-toolbar custom></vxe-toolbar>
                <vxe-table
                        border
                        show-overflow
                        resizable
                        :tooltip-config="{theme:'light',enterable:true}"
                        highlight-hover-row
                        height="500"
                        size="medium"
                        align="center"
                        header-align="center"
                        :cell-style="cellStyle"
                        :row-style="rowStyle"
                        :loading="tableLoading"
                        :sort-config="{trigger: 'cell'}"
                        :data="newTableData">
                    <vxe-table-column type="seq" title="序号" width="60"></vxe-table-column>
                    <vxe-table-column :field="item.key" :title="item.title" min-width="120"
                                      v-for="(item,index) in tableTitle" :key="index">
                    </vxe-table-column>
                </vxe-table>

              </Col>
            </Row>
            <br>
            <Row type="flex" justify="end">
                <Col span="4">
                    <Button :disabled="nextBtnDisabled" v-show="state === 1" @click="nextStep">下一步</Button>
                </Col>
            </Row>
        </div>
        <div v-show="state === 2">
            <br>
            <Row type="flex" :gutter="16" justify="center">
                <Col span="4">
                    <Button long @click="prevStep">上一步</Button>
                </Col>
                <Col span="4">
                    <Button long icon="ios-cloud-upload-outline" @click="excelBtn">导入到数据库</Button>
                </Col>
            </Row>
        </div>
        <confirm-modal ref="confirmModal" :modal-show="confirmModalShow"
                       @cancelOption="cancelOption('cm')" @submitOption="submitOption('cm')"></confirm-modal>
        <review-modal ref="reviewModal" :table-column="failColumn" :table-data="failData"
                      :modal-show="reviewModalShow" @submitOption="submitOption('rm')"></review-modal>
        <Modal v-model="modalShow2" width="600" :closable="false">
            <div slot="header" style="color:#f60;text-align:center">
                <h3>导入数据在库中已存在，请删除后再进行导入</h3>
            </div>
            <div style="height: 300px; overflow-y: scroll; text-align: center;">
                <div style="margin-bottom: 5px">
                    <span style="font-weight: bold; display: inline-block;width: 40%;">姓名</span>
                    <span style="font-weight: bold; display: inline-block;width: 60%;">身份证号</span>
                </div>
                <div v-for="(item, index) in troubleData" :key="index">
                    <span style="display: inline-block;width: 40%;">{{item.name}}</span>
                    <span style="display: inline-block;width: 60%;">{{item.idcard}}</span>
                </div>
            </div>
            <div slot="footer">
                <Button type="error" size="large" @click="modalShow2 = false">确定</Button>
                <Button type="success" size="large" @click="delPepetitionIdcardData">忽略数据导入</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import excel from '@/libs/excel'
import { findDataByIdcards, getRecordById, saveExcelData, validateUniqueCardnoList, insertCardName } from '@/api/record'
import excelTemplate from '@/libs/excel-template'
import { handleRecord } from '@/libs/excel-handle'
import { validateAll, validateMaterial, validateRecord, validateWhiteList } from '@/libs/excel-validate'
import ConfirmModal from '@/components/excel-action-new/components/confirm-modal'
import ReviewModal from '@/components/excel-action-new/components/review-modal'

export default {
  name: 'excelActionNew',
  components: { ReviewModal, ConfirmModal },
  computed: {
    typeName () {
      switch (this.type) {
        case 'all':
          return '人员材料'
        case 'record':
          return '人员'
        case 'material':
          return '材料'
        case 'whiteList':
          return '白名单'
        default:
          return ' - '
      }
    }
  },
  props: {
    type: {
      type: String,
      default: () => {
        return ''
      }
    },
    archive_id: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  data () {
    return {
      state: 0, // 页面步骤标识
      confirmModalShow: false, // 导入最终确认框
      reviewModalShow: false, // 失败数据显示框
      troubleData: [], // 问题数据内容
      failData: [], // 失败数据内容
      failColumn: [
        {
          key: 'name',
          title: '姓名'
        },
        {
          key: 'idcard',
          title: '身份证号'
        },
        {
          key: 'title',
          title: '材料名称'
        },
        {
          key: 'dir',
          title: '文件夹名称'
        },
        {
          key: 'num',
          title: '文件数量'
        }
      ], // 失败数据表头
      modalShow2: false,
      uploadLoading: false,
      showRemoveFile: false,
      file: null,
      tableData: [],
      newTableData: [],
      saveTableData: [],
      tableTitle: [],
      progressPercent: 0,
      showProgress: false,
      tableLoading: false,
      nextBtnDisabled: false,
      templateHref: ''
    }
  },
  methods: {
    // modal取消操作
    cancelOption () {
      this.confirmModalShow = false
    },
    // modal确定操作
    submitOption (val) {
      switch (val) {
        case 'cm':
          this.modalSubmit()
          break
        case 'rm':
          this.reviewModalShow = false
          break
      }
    },
    cellStyle ({ row, rowIndex, column, columnIndex }) {
      if (!this.$common.xeUtils.isEmpty(row.cellClassName[column.property])) {
        if (row.cellClassName[column.property] === 'trouble-cell') {
          return {
            backgroundColor: '#FFEFE6',
            color: '#ED4014'
            // backgroundColor: '#187'
          }
        } else if (row.cellClassName[column.property] === 'trouble-cell-repeat') {
          return {
            backgroundColor: '#187',
            color: '#fff'
          }
        }
      }
    },
    rowStyle ({ row, rowIndex }) {
      if (row.rowClassName === 'absent') {
        return {
          backgroundColor: '#b0bbd3',
          color: '#0032a0'
          // backgroundColor: '#187'
        }
      }
    },
    getPeopleInfo () {
      getRecordById(this.archive_id).then(ret => {
        if (ret.data.errcode === 0) {
          this.personInfo = ret.data.data
        } else {
          this.$Message.error('获取信息失败，请检查网络！')
        }
      })
    },
    initTemplate () {
      switch (this.type) {
        case 'record':
          this.templateHref = excelTemplate.recordTemplate
          break
        case 'material':
          this.templateHref = excelTemplate.materialTemplate
          // 获取当前人员信息
          this.getPeopleInfo()
          break
        case 'whiteList':
          this.templateHref = excelTemplate.whiteListTemplate
          break
        case 'all':
          this.templateHref = excelTemplate.allTemplate
          break
      }
    },
    prevStep () {
      this.state = 1
    },
    nextStep () {
      this.state = 2
    },
    excelBtn () {
      this.confirmModalShow = true
    },
    // 身份证号组装处理
    autoCardnoHandle (val) {
      let cardnos = []
      val.forEach(item => {
        if (item.idcard) {
          cardnos.push(item.idcard)
        }
      })
      return cardnos
    },
    // 导入数据身份证号唯一校验
    validateUniqueCardno (val) {
      this.$refs.confirmModal.btnLoading = true
      validateUniqueCardnoList({ idcards: val }).then(ret => {
        let data = ret.data
        if (data.errcode === 0) {
          if (data.data.length > 0) {
            this.troubleData = data.data
            this.confirmModalShow = false
            this.$refs.confirmModal.btnLoading = false
            this.modalShow2 = true
          } else {
            this.saveExcelDataAction()
          }
        } else {
          this.$refs.confirmModal.btnLoading = false
          this.error(data)
        }
      })
    },
    delPepetitionIdcardData () {
      let idCardOList = []
      let saveData = []
      this.troubleData.forEach(item => {
        idCardOList[item.idcard.trim()] = true
      })
      this.saveTableData.forEach(item => {
        if (idCardOList[item.idcard.trim()] !== true) {
          saveData.push(item)
        }
      })
      this.saveTableData = saveData
      this.saveExcelDataAction()
    },
    saveExcelWhiteDataAction () {
      const tableData = this.saveTableData
      let param = { dataList: tableData }
      this.$refs.confirmModal.btnLoading = true
      insertCardName(param).then(ret => {
        let data = ret.data
        if (data.errcode === 0) {
          this.$refs.confirmModal.btnLoading = false
          this.confirmModalShow = false
          if (data.data.falseList && data.data.falseList.length > 0) {
            this.reviewModalShow = true
            this.failData = data.data.falseList
          } else {
            this.success(this.saveTableData.length)
          }
        } else {
          this.$refs.confirmModal.btnLoading = false
          this.error(data)
        }
      }).catch(ret => {
        this.modalLoading = false
        this.$Message.error('操作失败')
      })
    },
    // 保存导入数据
    saveExcelDataAction () {
      const tableData = this.saveTableData
      let param = {}
      switch (this.type) {
        case 'record':
          param = { type: this.type, dataList: tableData }
          break
        case 'material':
          param = { type: this.type, archive_id: this.archive_id, serial_number: this.personInfo.serial_number, dataList: tableData }
          break
        case 'all':
          param = { type: this.type, dataList: tableData }
          break
      }
      this.$refs.confirmModal.btnLoading = true
      saveExcelData(param).then(ret => {
        let data = ret.data
        if (data.errcode === 0) {
          this.$refs.confirmModal.btnLoading = false
          this.confirmModalShow = false
          if (data.data.falseList && data.data.falseList.length > 0) {
            this.reviewModalShow = true
            this.failData = data.data.falseList
          } else {
            this.success(this.saveTableData.length)
          }
        } else {
          this.$refs.confirmModal.btnLoading = false
          this.error(data)
        }
        // let data = ret.data
        // if (data.errcode === 0) {
        //   this.modalLoading = false
        //   this.success(tableData.length)
        //   this.confirmModalShow = false
        //   this.modalShow2 = false
        // } else {
        //   this.modalLoading = false
        //   this.error(data)
        // }
      }).catch(ret => {
        this.modalLoading = false
        this.$Message.error('操作失败')
      })
    },
    modalSubmit () {
      if (this.tableData.length === 0) {
        this.$Notice.warning({
          title: '请上传excel文件'
        })
      } else {
        switch (this.type) {
          case 'record':
            const idcards = this.autoCardnoHandle(this.tableData)
            this.validateUniqueCardno(idcards)
            break
          case 'material':
            this.saveExcelDataAction()
            break
          case 'whiteList':
            this.saveExcelWhiteDataAction()
            break
          case 'all':
            this.saveExcelDataAction()
            break
        }
      }
    },
    success (data) {
      if (data) {
        this.$Message.success('操作成功,共添加' + data + '条数据')
      } else {
        this.$Message.success('操作成功')
      }
    },
    error (data) {
      this.$Message.error({
        content: '操作失败,\n' + data.errmsg
      })
    },
    initUpload () {
      this.file = null
      this.state = 0
      this.tableData = []
      this.tableTitle = []
      this.nextBtnDisabled = false
      this.showProgress = false
    },
    handleUploadFile () {
      this.initUpload()
    },
    handleRemove () {
      this.initUpload()
      this.$Message.info('上传的文件已删除！')
      this.state = 0
    },
    handleBeforeUpload (file) {
      const fileExt = file.name.split('.').pop().toLocaleLowerCase()
      if (fileExt === 'xlsx' || fileExt === 'xls') {
        this.readFile(file)
        this.file = file
      } else {
        this.$Notice.warning({
          title: '文件类型错误',
          desc: '文件：' + file.name + '不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。'
        })
      }
      return false
    },
    // 读取文件
    readFile (file) {
      const reader = new FileReader()
      reader.readAsArrayBuffer(file)
      reader.onloadstart = e => {
        this.uploadLoading = true
        this.tableLoading = true
        this.state = 0
        this.showProgress = true
      }
      // reader.onprogress = e => {
      //   this.progressPercent = Math.round(e.loaded / e.total * 100)
      // }
      reader.onerror = e => {
        this.$Message.error('文件读取出错')
      }
      reader.onload = async e => {
        const data = e.target.result
        const { header, results } = excel.read(data, 'array')
        const tableTitle = header.map(item => {
          return { title: results[0][item], key: item, minWidth: 200, align: 'center' }
        })
        this.tableData = this.$common.xeUtils.clone(results)
        this.tableData.splice(0, 2) // 默认删除前两行数据
        let errorFlag = true
        let saveTableData = []
        let repeatArr = []
        const RN = window.localStorage.getItem('record_number').trim().toLowerCase()
        switch (this.type) {
          case 'record':
            this.tableData.forEach((item, index) => {
              item.cellClassName = { li_shu_guan_xi: '' }
              if (repeatArr[item.idcard]) {
                item.cellClassName.idcard = 'trouble-cell-repeat'
              } else {
                repeatArr[item.idcard] = true
              }
              // 针对无全宗号时候（模板错误）导致导入loading卡死的处理
              if (!item.record_number) {
                errorFlag = false
                return false
              }

              let result = validateRecord(item, index, RN)
              item = result.item
              if (result.error === true) {
                this.nextBtnDisabled = true
              }
              saveTableData.push(handleRecord(this.$common.xeUtils.clone(item)))
            })
            this.tableLoading = false
            break
          case 'material':
            for (let i = 0; i < this.tableData.length; i++) {
              this.tableData[i].cellClassName = { }
              if (repeatArr[this.tableData[i].dir]) {
                this.tableData[i].cellClassName.dir = 'trouble-cell-repeat'
              } else {
                repeatArr[this.tableData[i].dir] = true
              }
              // 针对无全宗号时候（模板错误）导致导入loading卡死的处理
              if (!this.tableData[i].record_number) {
                errorFlag = false
                return false
              }
              let result = await validateMaterial(this.tableData[i], i, RN)
              this.tableData[i] = result.item
              if (result.error === true) {
                this.nextBtnDisabled = true
              }
              saveTableData.push(this.$common.xeUtils.clone(this.tableData[i]))
            }
            // this.tableData.forEach(async (item, index) => {
            // })
            this.tableLoading = false
            break
          case 'whiteList':
            this.tableData.forEach((item, index) => {
              item.cellClassName = { }
              if (repeatArr[item.dir]) {
                item.cellClassName.dir = 'trouble-cell-repeat'
              } else {
                repeatArr[item.dir] = true
              }
              let result = validateWhiteList(item, index, RN)
              item = result.item
              if (result.error === true) {
                this.nextBtnDisabled = true
              }
              saveTableData.push(this.$common.xeUtils.clone(item))
            })
            this.tableLoading = false
            break
          case 'all':
            this.tableData.forEach((item, index) => {
              item.cellClassName = {}
              item.rowClassName = ''
            })
            this.beforeValidate(saveTableData)
            break
        }
        if (errorFlag) {
          this.newTableData = saveTableData
          this.saveTableData = saveTableData
          this.tableTitle = tableTitle
          this.uploadLoading = false
          // this.tableLoading = false
          this.showRemoveFile = true
          this.state = 1
          this.$Message.info('文件读取成功')
        } else {
          this.state = 0
          this.$Message.warning('请检查模板是否正确！')
        }
      }
    },
    // 针对人员材料全部导入 对人员信息校验前处理 获取信息
    beforeValidate (val) {
      // 根据身份证号数组去重
      const res = new Map()
      // 非重复表格数据
      let newArr = this.tableData.filter((a) => !res.has(a.idcard) && res.set(a.idcard, 1))
      // let repeatDir = []
      // 预处理非重复表格数据（dir）
      let repeatObj = {}
      newArr.forEach(item => {
        repeatObj[item.idcard] = []
      })
      // 组装身份证号
      const idcards = this.autoCardnoHandle(newArr)
      findDataByIdcards({ idcards: idcards }).then(ret => {
        let data = ret.data
        if (data.errcode === 0) {
          this.tableData.forEach((item, index) => {
            // 校验人员文件夹名称
            if (this.$common.xeUtils.includes(repeatObj[item.idcard], item.dir)) {
              item.cellClassName.dir = 'trouble-cell-repeat'
            } else {
              repeatObj[item.idcard].push(item.dir)
            }
            // 存在的人
            if (data.data[item.idcard] != null) {
              // 组装数据
              item.record_number = data.data[item.idcard].record_number
              item.serial_number = data.data[item.idcard].serial_number
              item.archive_id = data.data[item.idcard].id
              // 校验姓名
              if (data.data[item.idcard].name !== item.name) {
                item.name = item.name + ' （姓名不匹配）'
                item.cellClassName.name = 'trouble-cell'
                this.nextBtnDisabled = true
              }
            } else {
              // 不存在的人
              item.rowClassName = 'absent'
              this.nextBtnDisabled = true
            }

            let result = validateAll(item, index)
            item = result.item
            if (result.error === true) {
              this.nextBtnDisabled = true
            }
            val.push(this.$common.xeUtils.clone(item))
          })

          // console.log('表格', this.tableData)
          this.tableLoading = false
        } else {
          this.error(data)
        }
      })
    }
  },
  mounted () {
    this.initTemplate()
    // console.log('传入的类型', this.type)
  }
}
</script>

<style scoped>
    .out-style {
        padding: 10px;
        padding-bottom: 50px;
    }

    .tow-line-font {
        font-size: 14px;
    }

    .tow-line-font2 {
        text-decoration: underline;
        font-size: 14px;
        color: #40A7FF;
        font-weight: 600;
        cursor: pointer;
    }

    .step-style {
        margin-top: 30px;
        margin-bottom: 30px;
    }

    .four-line-font {
        font-size: 14px;
    }

    .last-line-upload {
        margin-top: 20px;
    }

    .last-line-upload >>> .ivu-upload-drag {
        height: 230px;
        background: #fff;
        border: 1px dashed #dcdee2;
        border-radius: 4px;
        text-align: center;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: border-color .2s ease;
    }

    .upload-tip {
        padding-top: 75px;
    }

</style>
